<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
</head>
<body>
<div class="addBrand-container" id="member-add-app">
  <div class="container">
    <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            :inline="false"
            label-width="180px"
            class="demo-ruleForm"
    >
      <el-form-item label="角色编码:" prop="rolecode">
        <el-input v-model="ruleForm.rolecode" placeholder="请输入角色编码" maxlength="20"/>
      </el-form-item>
      <el-form-item
              label="角色名称:"
              prop="rolename"
              v-if="showNew"
      >
        <el-input
                v-model="ruleForm.rolename"
                placeholder="请输入角色名称"
                maxlength="20"
        />
      </el-form-item>



      <div class="subBox address">
        <el-form-item>
          <el-button  @click="goBack5()">
            取消
          </el-button>

          <el-button
                  type="primary"
                  @click="validateCode()"
          >
            验证编码可用性
          </el-button>

          <el-button
                  type="primary"
                  @click="submitForm('ruleForm', false)"
                  v-if="showNew"
          >
            保存
          </el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../api/role.js"></script>
<script src="../../js/validate.js"></script>
<script src="../../js/index.js"></script>
<script>
  new Vue({
    el: '#member-add-app',
    data() {
      return {
        id: '',
        actionType : '',
        showNew: false,
        rolecodes: [],
        ruleForm : {
          rolecode:'',
          rolename: '',
        }
      }
    },
    computed: {
      rules () {
        return {
          rolecode: [{ required: true, 'validator': NotEmpty, 'trigger': 'blur' }],
          rolename: [{ required: true, 'validator': NotEmpty, 'trigger': 'blur' }],
        }
      }
    },
    created() {
      this.id = requestUrlParam('id')
      this.actionType = this.id ? 'edit' : 'add'
      if (this.id) {
        this.init()
      }
    },
    mounted() {
      this.getAllRolecode();
    },
    methods: {
      async init () {
        queryRoleById(this.id).then(res => {
          if (String(res.code) === '1') {
            this.ruleForm = res.data
          } else {
            this.$message.error(res.msg || '操作失败')
          }
        })
      },
      submitForm (formName, st) {
        if (this.validateCode()){
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.actionType === 'add') {
                const params = {
                  ...this.ruleForm,
                }
                addRole(params).then(res => {
                  if (res.code === 1) {
                    this.$message.success('角色添加成功！')
                    if (!st) {
                      this.goBack5()
                    } else {
                      this.ruleForm = {
                        rolecode:'',
                        rolename: '',
                      }
                    }
                  } else {
                    this.$message.error(res.msg || '操作失败')
                  }
                }).catch(err => {
                  this.$message.error('请求出错了：' + err)
                })
              } else {
                const params = {
                  ...this.ruleForm,
                }
                editRole(params).then(res => {
                  if (res.code === 1) {
                    this.$message.success('角色信息修改成功！')
                    this.goBack5()
                  } else {
                    this.$message.error(res.msg || '操作失败')
                  }
                }).catch(err => {
                  this.$message.error('请求出错了：' + err)
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }else {
          this.showNew = false
        }

      },
      validateCode() {
        if (this.ruleForm.rolecode===null || this.ruleForm.rolecode===""){
          this.$message.error('验证的角色编码不能为空！')
          this.showNew = false
        }else {

          var found = false; // 初始化found变量

          for (var i = 0; i < this.rolecodes.length; i++) {
            if (this.rolecodes[i] === this.ruleForm.rolecode) {
              found = true; // 如果找到了rolecode，将found变量设为true
              break; // 跳出循环
            }
          }
          if (!found) {
            this.$message.success('验证成功！角色编码可用')
            this.showNew = true
            return true
          } else {
            this.$message.error('验证失败！已存在角色编码')
            this.showNew = false
            return false
          }
        }
      },
      getAllRolecode () {
        return $axios({
          url: '/role/all/rolecode',
          method: 'get',
        }).then(response => {
          if (response.data && response.data.length) {
            this.rolecodes = response.data;
            console.info(this.rolecodes)
          }
        }).catch(error => {
          console.error(error);
        });
      },
      goBack5(){
        window.parent.menuHandle({
          id: '5',
          url: '/backend/page/role/list.html',
          name: '角色管理'
        },false)
      }
    }
  })
</script>
</body>
</html>